package com.authine.cloudpivot.ext.kingdee.work;

import com.alibaba.cola.dto.SingleResponse;
import com.authine.cloudpivot.ext.dto.kingDee.KingDeeBusiness;
import com.authine.cloudpivot.ext.dto.kingDee.request.*;
import com.authine.cloudpivot.ext.enums.kingdee.BusinessType;
import com.authine.cloudpivot.ext.enums.kingdee.FAccountIdEnum;
import com.authine.cloudpivot.ext.enums.kingdee.FormEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: liwei
 * @DateTime: 2021/7/16
 * @Description: TODO
 */
@Slf4j
public class MoneyWork extends BaseWork {


    //    平台付款：/create/payment
    public SingleResponse platformPayment( KingDeePlatFormPayment kingDeePlatFormPayment) {
        log.info("平台付款  request:{}", kingDeePlatFormPayment);
        //根据平台付款方式 获取对应的科目
        Integer subject = kingDeePlatFormPayment.getPaymentApplyType().subject;
        //银行账号
        String bankNo = kingDeePlatFormPayment.getBankNo();
        //付款时间
        Date confirmEndTime = kingDeePlatFormPayment.getConfirmEndTime();

        for (KingDeePlatFormPayments pay : kingDeePlatFormPayment.getPays()) {
            //付款单ID
            String id = pay.getId();
            //供应商名称
            String vendorName = pay.getVendorName();
            //供应商ID
            String vendorId = pay.getVendorId();
            //金融服务费
            BigDecimal financialServiceFee = pay.getFinancialServiceFee();
            //平台服务费
            BigDecimal platformServiceFee = pay.getPlatformServiceFee();
            //交易金额
            BigDecimal amountOfTheTransaction = pay.getAmountOfTheTransaction();
            //实际付款金额
            BigDecimal actualPaymentAmount = pay.getActualPaymentAmount();
            //平台服务金融费合计
            BigDecimal add = financialServiceFee.add(platformServiceFee);

            String remark = "采购发票号：" + pay.getNumber() + " - 付货款 - " + vendorName;

            List<FEntity> fEntityList = new ArrayList<>();

            //应付账款-云平台-供应商
            FEntity fEntity1 = FEntity.addFentity();
            fEntity1.setFExplanation(remark);
            fEntity1.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.payable0301.getFNumber()));
            fEntity1.setFDetailIdEntity(FDetailIdEntity.addFDetailID4(vendorId));
            fEntity1.setFDebit(actualPaymentAmount);
            fEntityList.add(fEntity1);

            //银行存款
            FEntity fEntity2 = FEntity.addFentity();
            fEntity2.setFExplanation(remark);
            fEntity2.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.getDes(subject)));
            fEntity2.setFDetailIdEntity(FDetailIdEntity.addBank(bankNo));
            fEntity2.setFCredit(actualPaymentAmount);

            fEntityList.add(fEntity2);

            KingDeeBusiness business = new KingDeeBusiness(id, null, BusinessType.PaymentRequest, confirmEndTime, null, kingDeePlatFormPayment.getAccountName());


            KingDeeEntity king = getKingDeeEntity(fEntityList,business);


            doSaveKingDeeAndRecord(FormEnum.VOUCHER, king, business);
        }
        log.info("平台付款  业务逻辑处理结束 <<<");

        return SingleResponse.buildSuccess();
    }



    //    平台取消付款：/cancel/payment
    public SingleResponse platformCancelPayment( List<KingDeeCancelPayment> kingDeeCancelPayments) {
        log.info("平台取消付款  request:{}", kingDeeCancelPayments);

        kingDeeCancelPayments.forEach(e -> {
            deleteRecordAndUpdate(e.getId(), BusinessType.PaymentRequest, e.getAccountName());
        });
        log.info("平台取消付款  业务逻辑处理结束 <<<");

        return SingleResponse.buildSuccess();
    }

    //    平台收款：/create/collection
    public SingleResponse platformCollection( KingDeePlatformCollection collection) {
        log.info("平台收款  request:{}", collection);
        //获取付款方式对应的金蝶编码
        Integer subject = collection.getPaymentApplyType().subject;
        //付款账号
        String bankNo = collection.getCollectionAccount();
        //收款单id
        String payId = collection.getReceiptNumber();
        //客户名称
        String client = collection.getPaymentClient();
        //金蝶编码
        String kingDeeCode = getKingDeeCode(client);
        //客户id
        String clientId = collection.getPaymentClientId();
        //总金额
        BigDecimal amount = collection.getPaymentAmount();
        //收款时间
        Date collectionTime = collection.getCollectionTime();
        //
        String remark = "收款单号：" + payId + "--收货款--" + client;

        List<FEntity> fEntityList = new ArrayList<>();
        String contractPaymentType = collection.getContractPaymentType();

        int i = 30;
        if (StringUtils.isNotBlank(contractPaymentType)) {

            if (contractPaymentType.equals("商品账单")) {
                //商品账单
                i = 35;
            } else if (contractPaymentType.equals("服务费")) {
                //服务费
                i = 36;

            }
        }

        //银行存款
        FEntity fEntity1 = FEntity.addFentity();
        fEntity1.setFExplanation(remark);
        fEntity1.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.getDes(subject)));
        if (StringUtils.isNotBlank(bankNo)) {
            fEntity1.setFDetailIdEntity(FDetailIdEntity.addBank(bankNo));
        }
        fEntity1.setFDebit(amount);
        fEntityList.add(fEntity1);

        //应付账款-云平台-供应商
        FEntity fEntity2 = FEntity.addFentity();
        fEntity2.setFExplanation(remark);
        fEntity2.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.getDes(i)));
        fEntity2.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingDeeCode));
        fEntity2.setFDebit(amount);
        fEntityList.add(fEntity2);

        KingDeeBusiness business = new KingDeeBusiness(payId, null, BusinessType.CollectionApplyForm, collectionTime, null, collection.getAccountName());

        KingDeeEntity king = getKingDeeEntity(fEntityList,business);

        doSaveKingDeeAndRecord(FormEnum.VOUCHER, king, business);
        log.info("平台收款  业务逻辑处理结束 <<<");

        return SingleResponse.buildSuccess();
    }

    //    取消收款：/cancel/collection
    public SingleResponse platformCancelCollection( List<KingDeeCancelPayment> kingDeeCancelPayments) {
        log.info("取消收款  request:{}", kingDeeCancelPayments);

        kingDeeCancelPayments.forEach(e->{
            deleteRecordAndUpdate(e.getId(),BusinessType.CollectionApplyForm,e.getAccountName());
        });
        log.info("取消收款  业务逻辑处理结束 <<<");

        return SingleResponse.buildSuccess();
    }

    /*    平台退款：/return/collection */
    public SingleResponse platformReturnCancelPayment( KingDeePlatformCollection collection) {
        log.info("平台退款  request:{}", collection);
        //获取收款方式对应的金蝶编码
        Integer subject = collection.getPaymentApplyType().subject;
        //付款账号
        String bankNo = collection.getCollectionAccount();
        //付款单ID
        String payId = collection.getReceiptNumber();
        //付款客户名称
        String client = collection.getPaymentClient();
        //金蝶编码
        String kingDeeCode = getKingDeeCode(client);
        //付款账户ID
        String clientId = collection.getPaymentClientId();
        //收款总金额
        BigDecimal amount = collection.getPaymentAmount();
        //收款时间
        Date collectionTime = collection.getCollectionTime();
        String accountName = collection.getAccountName();

        String remark = "收款单号："+payId+"--退货款--"+client;

        List<FEntity> fEntityList = new ArrayList<>();

        //银行存款
        FEntity fEntity1 = FEntity.addFentity();
        fEntity1.setFExplanation(remark);
        fEntity1.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.getDes(subject)));
        if (StringUtils.isNotBlank(bankNo)) {
            fEntity1.setFDetailIdEntity(FDetailIdEntity.addBank(bankNo));
        }
        fEntity1.setFDebit(amount.negate());
        fEntityList.add(fEntity1);

        //应付账款-云平台-供应商
        FEntity fEntity2 = FEntity.addFentity();
        fEntity2.setFExplanation(remark);
        fEntity2.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.accounts0601.getFNumber()));
        fEntity2.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingDeeCode));
        fEntity2.setFCredit(amount);
        fEntityList.add(fEntity2);

        KingDeeBusiness business = new KingDeeBusiness(payId, null, BusinessType.CollectionReturnApplyForm, collectionTime, null, accountName);
        KingDeeEntity kingDeeEntity = getKingDeeEntity(fEntityList, business);
        doSaveKingDeeAndRecord(FormEnum.VOUCHER,kingDeeEntity,business);
        log.info("平台退款  业务逻辑处理结束 <<<");

        return SingleResponse.buildSuccess();
    }

    /*  平台取消退款：/cancel/return/collection */
    public SingleResponse platformCancelReturnCancelPayment( List<KingDeeCancelPayment> kingDeeCancelPayments) {
        log.info("平台取消退款  request:{}", kingDeeCancelPayments);

        kingDeeCancelPayments.forEach(e->{
            deleteRecordAndUpdate(e.getId(),BusinessType.CollectionReturnApplyForm,e.getAccountName());
        });
        log.info("平台取消退款  业务逻辑处理结束 <<<");

        return SingleResponse.buildSuccess();
    }

    /* 平台核销：/write/off */
    public SingleResponse platformWriteOff( KingDeePlatformWriteOff kingDeePlatformWriteOff) {
        log.info("平台核销  request:{}", kingDeePlatformWriteOff);

        //付款抬头
        String paymentPayable = kingDeePlatformWriteOff.getPaymentPayable();
        //摘要
        String remark = "收获款--"+paymentPayable;
        //付款单ID
        String payId = kingDeePlatformWriteOff.getReceiptId();
        //收款时间
        Date receiptTime = kingDeePlatformWriteOff.getReceiptTime();
        //账套名称
        String accountName = kingDeePlatformWriteOff.getAccountName();

        List<FEntity> fEntityList = new ArrayList<>();

        FEntity fEntity1 = FEntity.addFentity();
        fEntity1.setFExplanation(remark);
        fEntity1.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.accounts0601.getFNumber()));
        fEntity1.setFDetailIdEntity(FDetailIdEntity.addDetailID6(paymentPayable));
        fEntity1.setFCredit(kingDeePlatformWriteOff.getWriteOffAmount().negate());
        fEntityList.add(fEntity1);

        for (KingDeePlatformWriteOffInvoiceDetail detail : kingDeePlatformWriteOff.getKingDeePlatformWriteOffInvoiceDetailList()) {

            String kingDeeCode = getKingDeeCode(detail.getInvoice());

            FEntity fEntity2 = FEntity.addFentity();
            fEntity2.setFExplanation(remark);
            fEntity2.setFAccountId(FAccountIdEntity.faccount(FAccountIdEnum.accounts0601.getFNumber()));
            fEntity2.setFDetailIdEntity(FDetailIdEntity.addDetailID6(kingDeeCode));
            fEntity2.setFCredit(detail.getAmount());
            fEntityList.add(fEntity2);
        }


        KingDeeBusiness business = new KingDeeBusiness(payId,null,BusinessType.PlatformWriteOff,receiptTime,null,accountName);

        KingDeeEntity kingDeeEntity = getKingDeeEntity(fEntityList, business);

        doSaveKingDeeAndRecord(FormEnum.VOUCHER,kingDeeEntity,business);
        log.info("平台核销  业务逻辑处理结束 <<<");

        return SingleResponse.buildSuccess();
    }

    /* 平台取消核销：/cancel/write/off */
    public SingleResponse platformCancelWriteOff( List<KingDeeCancelPayment> kingDeeCancelPayments) {
        log.info("平台取消核销  request:{}", kingDeeCancelPayments);

        kingDeeCancelPayments.forEach(e->{
            deleteRecordAndUpdate(e.getId(),BusinessType.PlatformWriteOff,e.getAccountName());
        });
        log.info("平台取消核销  业务逻辑处理结束 <<<");

        return SingleResponse.buildSuccess();
    }
}
